function downAdjust(arr, parentIndex, length) {
    const temp = arr[parentIndex];
    let childIndex = 2 * parentIndex + 1; // left
    while (childIndex < length) {
        if (childIndex + 1 < length && arr[childIndex + 1] > arr[childIndex]) {
            childIndex++;
        }
        if (temp >= arr[childIndex]) {
            break;
        }
        arr[parentIndex] = arr[childIndex];
        parentIndex = childIndex;
        childIndex = 2 * childIndex + 1;
    }
    arr[parentIndex] = temp;
}

function heapSort(arr) {
    // 无序数组 --> 最大堆
    // 套路：让所有非叶子节点下沉
    for (let i = Math.floor((arr.length - 2) / 2); i >= 0; i--) {
        downAdjust(arr, i, arr.length);
    }
    for (let i = arr.length - 1; i > 0; i--) {
        const temp = arr[i];
        arr[i] = arr[0];
        arr[0] = temp;
        downAdjust(arr, 0, i);
    }
}

const arr = [1,3,2,6,5,7,8,9,10,0];
heapSort(arr);
console.log(arr);